package Reactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

public class ReactorServer {

    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 9999;

    //构造器,完成初始化
    public ReactorServer() {
        try{
            //得到选择器
            selector = Selector.open();
            //获取ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞
            listenChannel.configureBlocking(false);
            //讲该listenChannel注册到serlector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public void listen() {
        try {
            //循环处理
            while (true) {
                int count = selector.select();
                if (count > 0){
                    //遍历得到的selectionkey的集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();

                        //监听到accept
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            sc.register(selector,SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress() + "上线");
                        }
                        if (key.isReadable()) {
                            //读取
                            readData(key);
                        }

                        iterator.remove();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //读取客户端消息
    private void readData(SelectionKey key) {
        SocketChannel channel = null;
        try {
            //得到channel
            channel = (SocketChannel) key.channel();

            //创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            //读
            int count = channel.read(buffer);

            //根据count处理
            if (count > 0) {
                //把缓存区数据转换成字符串
                String msg = new String(buffer.array());
                System.out.println("from 客户端:" + msg);

                JDBC jdbc = new JDBC();
                Date date = new Date();
                SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
                String time = dateFormat.format(date);
                jdbc.accept();
                jdbc.insert(1,"name",time,msg);
                jdbc.close();
                //需要向其他客户端转发
                sendInfoToOtherClients(msg, channel);
            }

        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "下线了....");

                //取消注册
                key.cancel();

                //关闭channel
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    //转发消息
    private void sendInfoToOtherClients (String msg,SocketChannel self) throws IOException{
        System.out.println("服务器转发消息.....");
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel = key.channel();
            if (targetChannel instanceof  SocketChannel && targetChannel != self) {
                SocketChannel dest = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());

                dest.write(buffer);
            }
        }

    }
    public static void main(String[] args) {
        ReactorServer server = new ReactorServer();
        server.listen();
    }
}
